/**
 * Copyright (c) 2018 小润科技 All rights reserved.

 * 版权所有，侵权必究！
 */

package com.xr.sy.modules.security.controller;

import com.xr.common.exception.ErrorCode;
import com.xr.common.exception.SyException;
import com.xr.common.utils.Result;
import com.xr.common.validator.AssertUtils;
import com.xr.common.validator.ValidatorUtils;
import com.xr.sy.modules.log.service.SysLogLoginService;
import com.xr.sy.modules.message.email.EmailUtils;
import com.xr.sy.modules.message.entity.SysMailEntity;
import com.xr.sy.modules.message.service.SysMailService;
import com.xr.sy.modules.message.service.SysMailTemplateService;
import com.xr.sy.modules.security.user.SecurityUser;
import com.xr.sy.modules.security.user.UserDetail;
import com.xr.sy.modules.sys.dto.SysUserDTO;
import com.xr.sy.modules.sys.enums.UserStatusEnum;
import com.xr.sy.modules.security.dto.LoginDTO;
import com.xr.sy.modules.security.password.PasswordUtils;
import com.xr.sy.modules.security.service.CaptchaService;
import com.xr.sy.modules.sys.service.SysUserService;
import com.xr.sy.modules.security.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录
 */
@RestController
@Api(tags="登录管理")
public class LoginController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private CaptchaService captchaService;
	@Autowired
	private SysMailService sysMailService;


	@GetMapping("captcha")
	@ApiOperation(value = "验证码", produces="application/octet-stream")
	@ApiImplicitParam(paramType = "query", dataType="string", name = "uuid", required = true)
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		//uuid不能为空
		AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);

		//生成图片验证码
		BufferedImage image = captchaService.create(uuid);

		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		out.close();
	}

	@PostMapping("login")
	@ApiOperation(value = "登录")
	public Result login(HttpServletRequest request, @RequestBody LoginDTO login) {
		//效验数据
		ValidatorUtils.validateEntity(login);

		//验证码是否正确
		boolean flag = captchaService.validate(login.getUuid(), login.getCaptcha());
		if(!flag){
			return new Result().error(ErrorCode.CAPTCHA_ERROR);
		}

		//用户信息
		SysUserDTO user = sysUserService.getByUsername(login.getUsername());


		//用户不存在
		if(user == null){
			throw new SyException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
		}

		//密码错误
		if(!PasswordUtils.matches(login.getPassword(), user.getPassword())){
			throw new SyException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
		}

		//账号停用
		if(user.getStatus() == UserStatusEnum.DISABLE.value()){
			throw new SyException(ErrorCode.ACCOUNT_DISABLE);
		}

		//登录成功
		return sysUserTokenService.createToken(user);
	}

	@PostMapping("user/login")
	@ApiOperation(value = "前台用户登录")
	public Result userLogin(String email, String verifyCode) {
		//验证码是否正确
		boolean flag = captchaService.validate(email, verifyCode);
		if(!flag){
			return new Result().error(ErrorCode.CAPTCHA_ERROR);
		}

		//用户信息
		SysMailEntity mailEntity = sysMailService.getByMail(email);
		//用户不存在
		if(mailEntity == null){
			throw new SyException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
		}
		//账号停用
		if(mailEntity.getStatus() == UserStatusEnum.DISABLE.value()){
			throw new SyException(ErrorCode.ACCOUNT_DISABLE);
		}

		//登录成功
		SysUserDTO user = new SysUserDTO();
		user.setUsername(email);
		user.setEmail(mailEntity.getName());

		return sysUserTokenService.createToken(user);
	}

	@PostMapping("logout")
	@ApiOperation(value = "退出")
	public Result logout(HttpServletRequest request) {
		UserDetail user = SecurityUser.getUser();

		//退出
		sysUserTokenService.logout(user.getId());

		//用户信息
		return new Result();
	}
	
}